/* Copyright (c) 2004-2024 peigen.info. All rights reserved. */

package info.peigen.hotpot.manage.core.manage.repository.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import info.peigen.hotpot.common.core.result.ResultCode;
import info.peigen.hotpot.common.service.base.exception.BusinessException;
import info.peigen.hotpot.component.data.repository.beetlsql.service.AbstractBeetlSqlRepository;
import info.peigen.hotpot.manage.core.domain.User;
import info.peigen.hotpot.manage.core.manage.convertor.UserManageConvertor;
import info.peigen.hotpot.manage.core.manage.repository.mapper.UserManageMapper;
import info.peigen.hotpot.manage.core.repository.entity.UserEntity;
import org.noear.solon.annotation.Component;

import java.util.List;

/**
 * <b>(UserManageRepository)</b>
 * 管理后台 "用户" 仓储服务
 *
 * @author Peigen
 * @version 1.0.0
 * @since 2024-08-02
 */
@SuppressWarnings("unused")
@Component
public class UserManageRepository extends AbstractBeetlSqlRepository<UserManageMapper, UserEntity> {
    public User active(String userId) {
        Assert.isTrue(StrUtil.isNotEmpty(userId), () -> new BusinessException(ResultCode.FAILURE, "激活时[userId]不得为空!"));
        UserEntity entity = getMapper().findByUserId(userId);
        Assert.notNull(entity, () -> new BusinessException(ResultCode.FAILURE, "激活失败!userId=" + userId));
        return UserManageConvertor.INSTANCE.convertToDomain(entity);
    }

    public User lock(String userId) {
        Assert.isTrue(StrUtil.isNotEmpty(userId), () -> new BusinessException(ResultCode.FAILURE, "加锁时[userId]不得为空!"));
        UserEntity entity = getMapper().lockByUserId(userId);
        Assert.notNull(entity, () -> new BusinessException(ResultCode.FAILURE, "锁定失败!userId为空!"));
        return UserManageConvertor.INSTANCE.convertToDomain(entity);
    }

    public void removeByUserId(String userId) {
        Assert.isTrue(StrUtil.isNotEmpty(userId), () -> new BusinessException(ResultCode.FAILURE, "删除时[userId]不得为空!"));
        getMapper().deleteByUserId(userId);
    }

    public void removeByIds(List<Integer> ids) {
        Assert.isTrue(CollUtil.isNotEmpty(ids), () -> new BusinessException(ResultCode.FAILURE, "删除时[id]不得为空!"));
        getMapper().deleteByIds(ids);
    }

    public void logicDeleteById(Integer id) {
        delete(id);
    }

    public int logicDeleteByUserId(String userId) {
        Assert.isTrue(StrUtil.isNotEmpty(userId), () -> new BusinessException(ResultCode.FAILURE, "逻辑删除时[userId]不得为空!"));
        return getMapper().createLambdaQuery().andEq(UserEntity::getUserId, userId).delete();
    }

    public void store(User domain) {
        Assert.isTrue(ObjectUtil.isNotEmpty(domain), () -> new BusinessException(ResultCode.FAILURE, "持久化时[domain]不得为空!"));
        UserEntity entity = UserManageConvertor.INSTANCE.convertToEntity(domain);
        saveOrUpdate(entity);
    }

}